package cn.wing.gui;

import cn.wing.event.OpenSharedMenuPacket;
import cn.wing.event.TransactionInfoMapSync;
import cn.wing.items.SaleItem;
import cn.wing.key.KeyInit;
import cn.wing.utils.TransactionInfo;
import com.mojang.blaze3d.systems.RenderSystem;
import net.minecraft.client.Minecraft;
import net.minecraft.client.gui.GuiGraphics;
import net.minecraft.client.gui.components.Button;
import net.minecraft.client.gui.components.EditBox;
import net.minecraft.client.gui.screens.inventory.AbstractContainerScreen;
import net.minecraft.network.chat.Component;
import net.minecraft.resources.ResourceLocation;
import net.minecraft.world.entity.player.Inventory;
import net.minecraft.world.inventory.ClickType;
import net.minecraft.world.inventory.Slot;
import net.minecraft.world.item.ItemStack;
import net.minecraft.world.item.Items;
import org.jetbrains.annotations.NotNull;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.List;

import static cn.wing.PlayTradingMain.*;
import static cn.wing.constant.GuiConstant.TRANSACTION_INFO_MAP;

public class TradingScreen extends AbstractContainerScreen<TradingMenu> {

    private static final Logger log = LoggerFactory.getLogger(TradingScreen.class);

    public TradingScreen(TradingMenu p_97741_, Inventory p_97742_, Component p_97743_) {
        super(p_97741_, p_97742_, p_97743_);
    }

    private String clickItem;

    private int hash = -1;
    private int w = 0, h = 0;

    private static final ResourceLocation play_trading = ResourceLocation.parse(MOD_ID+":textures/gui/play_trading.png");

    @Override
    public void render(@NotNull GuiGraphics p_281549_, int p_281550_, int p_282878_, float p_282465_) {
        this.renderBackground(p_281549_);
        super.render(p_281549_, p_281550_, p_282878_, p_282465_);
        this.renderTooltip(p_281549_, p_281550_, p_282878_);
        p_281549_.renderItem(new ItemStack(Items.EMERALD), leftPos + 71, topPos + 20);
    }

    @Override
    protected void renderLabels(GuiGraphics p_281635_, int p_282681_, int p_283686_) {
        inventoryLabelX = 7;
        inventoryLabelY = 39;
        super.renderLabels(p_281635_, p_282681_, p_283686_);

        if (hash == TRANSACTION_INFO_MAP.hashCode() && w == width && h == height) {
            return;
        }
        clearWidgets();
        init();
        int widthCount = width / 3 / 17;
        int sum = widthCount * (height / 17);
        List<TransactionInfo> transactionInfos = TRANSACTION_INFO_MAP.values().stream().sorted((v1, v2) -> {
            if (v2.getPlayer() != v1.getPlayer()) {
                return v2.getPlayer().compareTo(v1.getPlayer());
            }
            else if (v2.getSellItemStack().getItem().toString().compareTo(v1.getSellItemStack().getItem().toString()) != 0) {
                return v2.getSellItemStack().getItem().toString().compareTo(v1.getSellItemStack().getItem().toString());
            } else {
                return v2.getSellItemStack().getCount() - v1.getSellItemStack().getCount();
            }
        }).toList();

        int x = 0, y = 0, i = 0, j = 0;
        for (;i < sum && i < transactionInfos.size(); i++) {
            TransactionInfo transactionInfo = transactionInfos.get(i);
            StringBuilder tooltip = new StringBuilder();
            for (ItemStack itemStack : transactionInfo.getBuyItemStack()) {
                tooltip.append(itemStack.getItem().getDescription().getString()).append(itemStack.getCount()).append("\n");
            }
            addRenderableWidget(new SaleItem(x, y,18,18, Component.literal(tooltip.toString()), transactionInfo, (v) -> clickItem = v.getUuid()));
            if (++j >= widthCount) {
                x = 0;
                y+=18;
                j = 0;
            } else {
                x += 18;
            }
        }
        hash = TRANSACTION_INFO_MAP.hashCode();
        w = width;
        h = height;
    }

    @Override
    protected void renderBg(GuiGraphics p_283065_, float p_97788_, int p_97789_, int p_97790_) {
        RenderSystem.enableBlend();
        RenderSystem.defaultBlendFunc();
//        p_283065_.blit(BG, 0, 0, 0, 0, width, height, width, height);
        int i = (this.width - this.imageWidth) / 2;
        int j = (this.height - this.imageHeight) / 2;
        p_283065_.blit(play_trading, i, j, 0, 0, 256, 256);
    }


    @Override
    protected void init() {
        this.imageHeight = 133;
        super.init();

        EditBox emeraldNum = new EditBox(Minecraft.getInstance().font, leftPos+70, topPos+35, 16, 7, Component.translatable(""));
        this.setInitialFocus(emeraldNum);
        emeraldNum.setValue("1");
        emeraldNum.setFilter((s ->
                s.isEmpty() ||   // 允许删空
                        s.equals("0") ||   // 允许单个 0
                        s.matches("[1-9]\\d*")                 // 非 0 开头数字
        ));
        addRenderableWidget(emeraldNum);

        addRenderableWidget(Button.builder(Component.translatable("submitButton"), p_93751_ -> {
            if (menu.getSlot(0).hasItem()) {
                SUB_CHANNEL.sendToServer(new OpenSharedMenuPacket(true, Integer.parseInt(emeraldNum.getValue())));
            }
            hash = -1;
        }).bounds(leftPos , topPos+132, 30,10).build());

        addRenderableWidget(Button.builder(Component.translatable("ok"), p_93751_ -> {
            if (clickItem == null) {
                return;
            }
            TRANSACTION_INFO_MAP_CHANNEL.sendToServer(new TransactionInfoMapSync(clickItem, null));
            clickItem = null;
            hash = -1;
        }).bounds(leftPos+145, topPos+132, 30,10).build());


//        for (Item item : ForgeRegistries.ITEMS) {
//            TRANSACTION_INFO_MAP.put(UUID.randomUUID().toString(), new TransactionInfo(Minecraft.getInstance().player, new ItemStack(item),Lists.newArrayList(), "xxx"));
//        }
    }

    @Override
    protected void slotClicked(Slot p_97778_, int p_97779_, int p_97780_, ClickType p_97781_) {

        super.slotClicked(p_97778_, p_97779_, p_97780_, p_97781_);
    }

    @Override
    public boolean mouseClicked(double p_97748_, double p_97749_, int p_97750_) {
        return super.mouseClicked(p_97748_, p_97749_, p_97750_);
    }

    @Override
    public boolean keyPressed(int p_97765_, int p_97766_, int p_97767_) {

        super.keyPressed(p_97765_, p_97766_, p_97767_);
        if (KeyInit.OPEN_GUI_KEY.matches(p_97765_, p_97766_) || p_97765_ == 256) {
            Minecraft.getInstance().setScreen(null);
        }
        return true;
    }

}
